<script setup>
import {
  queryProductsByTotalPopularity,
  getBrandById
} from '@/apis/popularityRanking.js'
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const brandGroups = ref({})
const pageNum = ref(1)
const pageSize = ref(100) // 获取所有数据
const loading = ref(false)
const finished = ref(false)

// 添加品牌信息缓存
const brandNames = ref({})

// 查询品牌信息
const queryBrandNames = async (brandIds) => {
  try {
    const promises = brandIds.map((id) => getBrandById(id))
    const results = await Promise.allSettled(promises)

    results.forEach((result, index) => {
      if (result.status === 'fulfilled' && result.value.code === 200) {
        const brand = result.value.data
        brandNames.value[brandIds[index]] = brand.name
      } else {
        brandNames.value[brandIds[index]] = '未知品牌'
      }
    })
  } catch (error) {
    console.error('查询品牌信息失败:', error)
  }
}

// 修改查询商品方法
const queryProducts = async () => {
  if (loading.value || finished.value) return

  try {
    loading.value = true
    const res = await queryProductsByTotalPopularity(
      pageNum.value,
      pageSize.value
    )

    if (res.code === 200 && res.data) {
      const list = res.data.list || []

      // 按品牌分组并排序
      brandGroups.value = list.reduce((groups, item) => {
        if (!groups[item.brandId]) {
          groups[item.brandId] = []
        }
        groups[item.brandId].push(item)
        return groups
      }, {})

      // 对每个品牌组内的商品按 totalPopularity 排序
      for (const brandId in brandGroups.value) {
        brandGroups.value[brandId].sort(
          (a, b) => b.totalPopularity - a.totalPopularity
        )
      }

      // 查询所有品牌的名称
      const brandIds = Object.keys(brandGroups.value)
      await queryBrandNames(brandIds)

      finished.value = true
    } else {
      finished.value = true
      ElMessage.warning(res.msg || '暂无数据')
    }
  } catch (error) {
    console.error('查询失败', error)
    ElMessage.error('加载失败，请重试')
    finished.value = true
  } finally {
    loading.value = false
  }
}

// 处理品牌ID
const handleBrandId = () => {
  const brandId = route.query.brandId
  if (brandId && brandGroups.value[brandId]) {
    brandGroups.value = { [brandId]: brandGroups.value[brandId] }
  }
}

onMounted(() => {
  queryProducts().then(() => {
    handleBrandId()
  })
})

// 改进的文本截断方法
const truncateText = (text, length = 12) => {
  if (!text) return ''

  // 计算字符串的"视觉长度"
  const getVisualLength = (str) => {
    let len = 0
    for (let i = 0; i < str.length; i++) {
      // 中文字符、全角符号等占两个单位
      if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
        len += 2
      } else {
        // 英文字母、数字、半角符号等占一个单位
        len += 1
      }
    }
    return len
  }

  // 如果视觉长度小于等于限制长度的2倍（因为中文字符占个单位），直接返回
  if (getVisualLength(text) <= length * 2) {
    return text
  }

  // 否则截取合适长度
  let len = 0
  let result = ''
  for (let i = 0; i < text.length; i++) {
    if (text.charCodeAt(i) > 127 || text.charCodeAt(i) === 94) {
      len += 2
    } else {
      len += 1
    }
    if (len <= length * 2) {
      result += text[i]
    } else {
      return result + '...'
    }
  }
  return result
}

// 跳转到分类页面
const goToCategory = (brandId) => {
  try {
    router.push({
      path: '/category/sub',
      query: { brandId: brandId }
    })
  } catch (error) {
    console.error('导航错误:', error)
    ElMessage.error('页面跳转失败')
  }
}

// 跳转到商品详细页面
const goToProductDetail = (productId) => {
  try {
    router.push({
      path: `/detail/${productId}`
    })
  } catch (error) {
    console.error('导航错误:', error)
    ElMessage.error('页面跳转失败')
  }
}
</script>

<template>
  <div class="container">
    <h2 class="page-title">人气商品榜单</h2>
    <div v-if="Object.keys(brandGroups).length > 0" class="brand-container">
      <div
        v-for="(goods, brandId) in brandGroups"
        :key="brandId"
        class="brand-block"
      >
        <div class="brand-header">
          <h3 class="brand-title">
            {{ brandNames[brandId] || '未知品牌' }}
          </h3>
          <el-button
            type="primary"
            class="more-link"
            @click="goToCategory(brandId)"
            :icon="ArrowRight"
          >
            查看更多
          </el-button>
        </div>
        <div class="brand-content">
          <!-- 左侧主打商品 -->
          <div
            class="main-product"
            v-if="goods[0]"
            @click="goToProductDetail(goods[0].id)"
          >
            <img :src="goods[0].picture" :alt="goods[0].productName" />
            <h4>{{ truncateText(goods[0].productName) }}</h4>
            <p class="desc">{{ goods[0].description }}</p>
            <p class="price">{{ goods[0].price }}元起</p>
          </div>
          <!-- 右侧商品网格 -->
          <div class="sub-products">
            <div
              v-for="good in goods.slice(1, 9)"
              :key="good.id"
              class="goods-item"
              @click="goToProductDetail(good.id)"
            >
              <div class="goods-image">
                <img :src="good.picture" :alt="good.productName" />
              </div>
              <h4 class="goods-name">{{ truncateText(good.productName) }}</h4>
              <p class="goods-desc">{{ good.description }}</p>
              <p class="goods-price">
                <span class="price">{{ good.price }}元起</span>
                <span v-if="good.oldPrice > good.price" class="old-price"
                  >{{ good.oldPrice }}元</span
                >
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-empty v-else-if="!loading" description="暂无数据" />
    <div class="loading-status" v-if="loading">
      <p class="loading-text">
        <el-icon class="is-loading"><Loading /></el-icon>
        加载中...
      </p>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  max-width: 1226px;
  margin: 0 auto;
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
}

.brand-block {
  background: #fff;
  margin-bottom: 30px;

  .brand-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 10px;

    .brand-title {
      font-size: 20px;
      font-weight: 500;
    }

    .more-link {
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 4px;

      &:hover {
        opacity: 0.9;
      }

      .el-icon {
        margin-left: 4px;
      }
    }
  }

  .brand-content {
    display: flex;
    gap: 20px;

    .main-product {
      width: 234px; // 大约是五分之一
      height: 614px;
      background: #fff;
      transition: all 0.3s;
      cursor: pointer;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
      }

      img {
        width: 100%;
        height: 460px;
        object-fit: cover;
      }

      h4 {
        font-size: 18px;
        margin: 10px;
      }

      .desc {
        font-size: 12px;
        color: #666;
        margin: 10px;
      }

      .price {
        color: var(--el-color-danger);
        font-size: 18px;
        font-weight: 500;
        margin: 10px;
      }
    }

    .sub-products {
      flex: 1;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 14px;

      .goods-item {
        background: #fff;
        padding: 20px;
        text-align: center;
        transition: all 0.3s;
        cursor: pointer;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
        }

        .goods-image {
          width: 160px;
          height: 160px;
          margin: 0 auto 10px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .goods-name {
          font-size: 14px;
          margin: 10px 0;
          font-weight: 500;
        }

        .goods-desc {
          font-size: 12px;
          color: #666;
          margin-bottom: 10px;
          height: 36px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .goods-price {
          .price {
            color: var(--el-color-danger);
            font-size: 16px;
            font-weight: 500;
            margin-right: 8px;
          }

          .old-price {
            color: #999;
            text-decoration: line-through;
            font-size: 12px;
          }
        }
      }
    }
  }
}

.loading-status {
  text-align: center;
  padding: 20px 0;
}
</style>
